/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CadastrarDespesa.java
 *
 * Created on 11/05/2009, 19:59:24
 */

package gerenciadorfinanceiro.view.resources;

import gerenciadorfinanceiro.Utilitario;
import gerenciadorfinanceiro.database.resources.Outcome;
import gerenciadorfinanceiro.database.resources.OutcomeSource;
import java.awt.event.KeyEvent;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import javax.swing.JOptionPane;
import org.jdesktop.application.Action;

/**
 *
 * @author eduardo
 */
public class CadastrarDespesa extends javax.swing.JDialog {

    /** Creates new form CadastrarDespesa */
    public CadastrarDespesa() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblDescricao = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtDescricao = new javax.swing.JTextArea();
        lblData = new javax.swing.JLabel();
        txtData = new javax.swing.JFormattedTextField();
        lblValor = new javax.swing.JLabel();
        lblFormaPagamento = new javax.swing.JLabel();
        cbxFormaPagamento = new javax.swing.JComboBox();
        btnGravar = new javax.swing.JButton();
        btnSair = new javax.swing.JButton();
        txtValor = new javax.swing.JFormattedTextField();
        lblRepeticoes = new javax.swing.JLabel();
        cbxRepeticoes = new javax.swing.JComboBox();

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(gerenciadorfinanceiro.GerenciadorFinanceiroApp.class).getContext().getResourceMap(CadastrarDespesa.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setModal(true);
        setName("Form"); // NOI18N
        setResizable(false);
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        lblDescricao.setText(resourceMap.getString("lblDescricao.text")); // NOI18N
        lblDescricao.setName("lblDescricao"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        txtDescricao.setColumns(20);
        txtDescricao.setRows(5);
        txtDescricao.setName("txtDescricao"); // NOI18N
        txtDescricao.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtDescricaoKeyPressed(evt);
            }
        });
        jScrollPane1.setViewportView(txtDescricao);

        lblData.setText(resourceMap.getString("lblData.text")); // NOI18N
        lblData.setName("lblData"); // NOI18N

        txtData.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM))));
        txtData.setName("txtData"); // NOI18N

        lblValor.setText(resourceMap.getString("lblValor.text")); // NOI18N
        lblValor.setName("lblValor"); // NOI18N

        lblFormaPagamento.setText(resourceMap.getString("lblFormaPagamento.text")); // NOI18N
        lblFormaPagamento.setName("lblFormaPagamento"); // NOI18N

        cbxFormaPagamento.setName("cbxFormaPagamento"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(gerenciadorfinanceiro.GerenciadorFinanceiroApp.class).getContext().getActionMap(CadastrarDespesa.class, this);
        btnGravar.setAction(actionMap.get("Salvar")); // NOI18N
        btnGravar.setText(resourceMap.getString("btnGravar.text")); // NOI18N
        btnGravar.setName("btnGravar"); // NOI18N

        btnSair.setAction(actionMap.get("Sair")); // NOI18N
        btnSair.setText(resourceMap.getString("btnSair.text")); // NOI18N
        btnSair.setName("btnSair"); // NOI18N

        txtValor.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0.00"))));
        txtValor.setName("txtValor"); // NOI18N

        lblRepeticoes.setText(resourceMap.getString("lblRepeticoes.text")); // NOI18N
        lblRepeticoes.setName("lblRepeticoes"); // NOI18N

        cbxRepeticoes.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24" }));
        cbxRepeticoes.setName("cbxRepeticoes"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnGravar, javax.swing.GroupLayout.PREFERRED_SIZE, 297, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(12, 12, 12)
                        .addComponent(btnSair, javax.swing.GroupLayout.DEFAULT_SIZE, 294, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblData)
                            .addComponent(lblValor)
                            .addComponent(lblFormaPagamento)
                            .addComponent(lblDescricao)
                            .addComponent(lblRepeticoes))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(cbxRepeticoes, 0, 448, Short.MAX_VALUE)
                            .addComponent(cbxFormaPagamento, 0, 448, Short.MAX_VALUE)
                            .addComponent(txtData, javax.swing.GroupLayout.DEFAULT_SIZE, 448, Short.MAX_VALUE)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 448, Short.MAX_VALUE)
                            .addComponent(txtValor, javax.swing.GroupLayout.DEFAULT_SIZE, 448, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblDescricao))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblData)
                    .addComponent(txtData, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblValor)
                    .addComponent(txtValor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblFormaPagamento)
                    .addComponent(cbxFormaPagamento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblRepeticoes)
                    .addComponent(cbxRepeticoes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnGravar)
                    .addComponent(btnSair))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtDescricaoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDescricaoKeyPressed
        int keyPressed = evt.getKeyCode();

        if (keyPressed == KeyEvent.VK_TAB) {
            txtData.requestFocus();
            evt.consume();
        }
    }//GEN-LAST:event_txtDescricaoKeyPressed

    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        this.LimparCampos();
    }//GEN-LAST:event_formComponentShown

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnGravar;
    private javax.swing.JButton btnSair;
    private javax.swing.JComboBox cbxFormaPagamento;
    private javax.swing.JComboBox cbxRepeticoes;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblData;
    private javax.swing.JLabel lblDescricao;
    private javax.swing.JLabel lblFormaPagamento;
    private javax.swing.JLabel lblRepeticoes;
    private javax.swing.JLabel lblValor;
    private javax.swing.JFormattedTextField txtData;
    private javax.swing.JTextArea txtDescricao;
    private javax.swing.JFormattedTextField txtValor;
    // End of variables declaration//GEN-END:variables

    public void carregarForm() {
        if (cbxFormaPagamento.getItemCount() == 0) {
            List sources = util.getOutcomeSourceDAO().getAllSources();

            for (Object o: sources) {
                cbxFormaPagamento.addItem(((OutcomeSource)o).getDescriptionSource());
            }
        }

        this.LimparCampos();
    }

    private Utilitario util;

    /**
     * @return the util
     */
    public Utilitario getUtil() {
        return util;
    }

    /**
     * @param util the util to set
     */
    public void setUtil(Utilitario util) {
        this.util = util;
    }

    @Action
    public void Sair() {
        this.setVisible(false);
        this.LimparCampos();
    }

    public void LimparCampos() {
        txtDescricao.setText("");
        txtData.setText("");
        txtValor.setText("");
        cbxFormaPagamento.setSelectedIndex(0);
        txtDescricao.requestFocus();
    }

    @Action
    public void Salvar() {
        int repeticoes = Integer.parseInt(cbxRepeticoes.getSelectedItem().toString());
        Date dataInicio = (Date)txtData.getValue();

        for(int vez = 0; vez < repeticoes; vez++)
        {
            Outcome despesa = new  Outcome();
            if (repeticoes == 1) {
                despesa.setDescriptionOutcome(txtDescricao.getText());
            } else {
                despesa.setDescriptionOutcome(txtDescricao.getText() + " - " + (vez+1) + " / " + repeticoes);
            }
            despesa.setData(new Date());
            Calendar c = new GregorianCalendar();
            c.setTime(dataInicio);
            c.roll(Calendar.MONTH, vez);
            despesa.setExpirationData(c.getTime());

            Object o = txtValor.getValue();
            Double valor;
            if (o.getClass().equals(Double.class)) {
                valor = (Double)o;
            } else if (o.getClass().equals(Long.class)) {
                double aux = ((Long)o).longValue();
                valor = aux;
            } else {
                JOptionPane.showMessageDialog(this, "Ocorreu um erro ao converter o valor da despesa.");
                return;
            }

            despesa.setValue(valor);
            despesa.setOwner(util.getLoggedUser());
            despesa.setSource(util.getOutcomeSourceDAO().getSourceByName((String)cbxFormaPagamento.getSelectedItem()));

            util.getOutcomeDAO().gravaOutcome(despesa);
        }
        JOptionPane.showMessageDialog(this, "Despesa gravada com sucesso !");
        Sair();

    }

}
